import os, cv2, math
import numpy as np


# 定义要遍历的文件夹路径
folder_path = "./"

init = 0


# 遍历文件夹下的所有文件和子文件夹
for root, dirs, files in os.walk(folder_path):

    num = 5 #int(math.sqrt(len(files)))
    col = 1
    row = 0

    # 遍历当前文件夹下的所有文件
    for file in files:
        # 判断文件是否以".png"结尾
        if file.endswith(".png"):
            # 处理PNG文件，例如打印文件名或读取图片信息等
            file_path = os.path.join(root, file)
            img = cv2.imread(file_path,cv2.IMREAD_UNCHANGED)

            if init == 0:
                channels = len(img.shape)
                if channels == 3:
                    h, w, c = img.shape
                    wmod = w % num
                    hmod = h % num
                    w_fit = int((w - wmod) / num)
                    h_fit = int((h - hmod) / num)

                    res = img[:h-hmod,:w-wmod,:]
                    s_img = cv2.resize(img,(w_fit,h_fit), interpolation = cv2.INTER_AREA)
                    res[0:h_fit,0:w_fit,:] = s_img
                elif channels == 2:
                    h, w = img.shape
                    wmod = w % num
                    hmod = h % num
                    w_fit = int((w - wmod) / num)
                    h_fit = int((h - hmod) / num)
                    res = img[:h-hmod,:w-wmod]
                    s_img = cv2.resize(img,(w_fit,h_fit), interpolation = cv2.INTER_AREA)
                    res[:h_fit,:w_fit] = s_img
                init = 1

            else:
                if channels == 3:
                    s_img = cv2.resize(img,(w_fit,h_fit), interpolation = cv2.INTER_AREA)
                    res[row*h_fit:(row+1)*h_fit, col*w_fit:(col+1)*w_fit,:] = s_img
                elif channels == 2:
                    s_img = cv2.resize(img,(w_fit,h_fit), interpolation = cv2.INTER_AREA)
                    res[row*h_fit:(row+1)*h_fit, col*w_fit:(col+1)*w_fit] = s_img
                col += 1
                if col >= num:
                    row +=1
                    col = 0
                    if row >= num:
                        cv2.imwrite(folder_path + 'res.png', res)
                        print('Concat done.')
                        exit()



